package com.noovo.comport.server;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.provider.Settings;
import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
import android.text.TextUtils;
import android.util.Log;

/**
 * tools for setting eth1
 * 
 * @author paul
 * @date 2015-4-13
 */
public class ProcessUtils {

	private final static boolean openDebug = false;

	public static List<String> execute(String command, long overtime) {
		debug("ProcessUtils command is : " + command);
		List<String> results = new ArrayList<String>();
		TimeOver over = new TimeOver();
		if (TextUtils.isEmpty(command)) {
			return null;
		}
		Process process = null;
		TimerThread timerThread = null;
		BufferedReader successReader = null;
		BufferedReader errorReader = null;
		StringBuilder errorMsg = null;

		try {
			process = Runtime.getRuntime().exec(command);
			timerThread = new TimerThread(process, over, overtime);
			timerThread.start();
			String lineStr;
			errorMsg = new StringBuilder();
			errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
			while ((lineStr = errorReader.readLine()) != null) {
				errorMsg.append(lineStr);
				debug("noovo command line error item : " + lineStr);
			}
			successReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
			while ((lineStr = successReader.readLine()) != null) {
				results.add(lineStr);
				debug("noovo command line success item : " + lineStr);
			}
			process.waitFor();

		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (over.getOver()) {
				results.add("OverTime");
			} else {
				try {
					if (successReader != null) {
						successReader.close();
					}
					if (errorReader != null) {
						errorReader.close();
					}
					if (process != null) {
						process.destroy();
						process = null;
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return results;
	}

	public static List<String> execute(List<String> cmds, int overtime) {
		List<String> results = new ArrayList<String>();
		DataOutputStream dos = null;
		BufferedReader successReader = null;
		BufferedReader errorReader = null;
		StringBuilder errorMsg = null;

		TimerThread timerThread = null;
		Process p = null;
		try {
			p = Runtime.getRuntime().exec("su");
			dos = new DataOutputStream(p.getOutputStream());
			for (int i = 0; i < cmds.size(); i++) {
				debug(cmds.get(i));
				dos.writeBytes(cmds.get(i) + "\n");
				dos.flush();
			}
			dos.writeBytes("exit\n");
			dos.flush();

			timerThread = new TimerThread(p, null, overtime);
			timerThread.start();

			String lineStr;
			errorMsg = new StringBuilder();
			errorReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
			while ((lineStr = errorReader.readLine()) != null) {
				errorMsg.append(lineStr);
				debug("noovo command line error item : " + lineStr);
			}
			successReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
			while ((lineStr = successReader.readLine()) != null) {
				results.add(lineStr);
				debug("noovo command line success item : " + lineStr);
			}
			p.waitFor();

		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (successReader != null)
					successReader.close();
				if (errorReader != null)
					errorReader.close();
				if (dos != null)
					dos.close();
				if (p != null) {
					p.destroy();
					p = null;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return results;
	}

	public static boolean isOverTime(List<String> results) {
		if (results.size() > 0) {
			String result = results.get(results.size() - 1);
			if (result.equals("OverTime"))
				return true;
		}
		return false;
	}

	public static String getFirstResult(List<String> results) {
		if (results.size() > 0) {
			return results.get(0);
		}
		return "";
	}

	public static String getAllResult(List<String> results) {
		if (results.size() > 0) {
			StringBuilder b = new StringBuilder();
			for (int i = 0; i < results.size(); i++) {
				b.append(results.get(i));
			}
			return b.toString();
		}
		return "";
	}

	public static void setInActivityTime(Context context, int seconds) {
		Settings.System.putInt(context.getContentResolver(), SCREEN_OFF_TIMEOUT, seconds * 1000);
	}
	
	/**
	 * DEBUG LOG
	 * 
	 * @param message
	 */
	private static void debug(String message) {
		if (openDebug) {
			Log.d(ComInfo.TAG, message);
		}
	}
}

class TimerThread extends Thread {
	Process p;
	TimeOver over;
	long overTime;
	boolean close = false;

	TimerTask task = new TimerTask() {
		public void run() {
			if (close)
				return;
			if (over != null) {
				over.setOver();
			}
			if (p != null) {
				p.destroy();
			}
		}
	};

	public TimerThread(Process p, TimeOver over, long overTime) {
		this.p = p;
		this.over = over;
		this.overTime = overTime;
	}

	public void setClose() {
		close = true;
	}

	public void run() {
		try {
			if (p == null)
				return;
			Timer timer = new Timer();
			timer.schedule(task, overTime);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

class TimeOver {
	boolean over = false;

	public void setOver() {
		over = true;
	}

	public boolean getOver() {
		return over;
	}
}